package com.chenggong.retrofit.rxjava;

import com.chenggong.retrofit.config.UrlConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 接口管理器
 */
public class ApiRxjavaServiceManager {

    private Retrofit mRetrofit;

    private static ApiRxjavaServiceManager mInstance = new ApiRxjavaServiceManager();

    public static ApiRxjavaServiceManager get() {
        return mInstance;
    }

    private ApiRxjavaServiceManager() {
        //创建Retrofit实例
        mRetrofit = new Retrofit.Builder()
                .baseUrl(UrlConfig.BASE_URL) //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器(支持Gson解析转换器)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())// 支持RxJava
                .client(getOkHttpClient())//OkHttpClient
                .build();
    }

    /**
     * 创建对应的ApiService
     *
     * @param service 接口类
     */
    public <T> T create(final Class<T> service) {
        return mRetrofit.create(service);
    }

    /** 获取Retrofit对象 */
    public Retrofit getRetrofit() {
        return mRetrofit;
    }


    /**
     * 获取一个OkHttpClient
     */
    private OkHttpClient getOkHttpClient() {
        //声明日志类
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        //设定日志级别
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(100, TimeUnit.SECONDS)//连接超时
                .writeTimeout(100, TimeUnit.SECONDS)//读取超时
                .readTimeout(100, TimeUnit.SECONDS)//写入超时
                .build();
    }
}


